#!/bin/bash

# reset_user_passwords.sh
# 功能说明:
# 1. 为指定的用户重置密码。
# 2. 支持通过命令行直接传入用户名，或者通过文件读取用户名列表。
# 3. 对于未指定新密码的用户，自动生成随机密码。
# 4. 自动将生成的随机密码保存到一个文件，方便管理员查阅。

# 随机密码生成函数
generate_random_password() {
  local length=12
  tr -dc 'A-Za-z0-9!@#$%^&*()-_=+' </dev/urandom | head -c $length
}

# 为用户设置密码
reset_password() {
  local username="$1"
  local new_password="$2"

  if id "$username" &>/dev/null; then
    echo "$username:$new_password" | sudo chpasswd
    if [[ $? -eq 0 ]]; then
      echo "Password for user $username has been successfully reset."
    else
      echo "Failed to reset password for user $username."
    fi
  else
    echo "User $username does not exist. Skipping..."
  fi
}

# 从文件读取用户并重置密码
process_file() {
  local file="$1"
  local output_file="$2"

  if [[ ! -f "$file" ]]; then
    echo "File $file does not exist. Please provide a valid file."
    exit 1
  fi

  while IFS= read -r line; do
    [[ -z "$line" || "$line" == \#* ]] && continue

    # 提取用户名和密码字段
    local username=$(echo "$line" | awk '{print $1}')
    local password=$(echo "$line" | awk '{print $2}')

    # 如果密码为空，则生成随机密码
    if [[ -z "$password" ]]; then
      password=$(generate_random_password)
    fi

    # 重置密码
    reset_password "$username" "$password"

    # 将用户和密码记录到输出文件
    echo "$username $password" >>"$output_file"
  done <"$file"
}

# 主函数
main() {
  if [[ $# -lt 1 ]]; then
    echo "Usage: $0 [-f user_file] [username1 username2 ...]"
    exit 1
  fi

  local output_file="reset_passwords_$(date +%Y%m%d%H%M%S).txt"
  echo "New passwords will be saved to: $output_file"

  case "$1" in
    -f|--file)
      shift
      if [[ -n "$1" ]]; then
        process_file "$1" "$output_file"
      else
        echo "Error: Missing file name after -f."
        exit 1
      fi
      ;;
    *)
      # 处理直接传入的用户名
      for username in "$@"; do
        local password=$(generate_random_password)
        reset_password "$username" "$password"
        echo "$username $password" >>"$output_file"
      done
      ;;
  esac

  echo "Password reset complete. Check $output_file for new passwords."
}

# 执行主函数
main "$@"

